package com.app.android.coliy.ui.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.android.coliy.R;
import com.app.android.coliy.adapter.MyBlueToothListAdapter;
import com.app.android.coliy.bean.LocalFileInfo;
import com.app.android.coliy.dialog.Print_Dialog;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.tool.CommToast;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.ui.view.MultiStateView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2018/6/20.
 */

public class BlueToothListActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String fileName = getIntent().getStringExtra("fileName");
        if (!TextUtils.isEmpty(fileName)) {
            List<LocalFileInfo> localFileList = DataSupport.findAll(LocalFileInfo.class);
            if (localFileList != null) {
                for (int i = 0; i < localFileList.size(); i++) {
                    if (fileName.equals(localFileList.get(i).filename)) {
                        localFileInfo = localFileList.get(i);
                        break;
                    }
                }
            }
        }
        setContentView(R.layout.activity_bluetoothlist);
        initView();

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始扫描
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//结束扫描
        filter.addAction(BluetoothDevice.ACTION_FOUND);             //发现设备
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);   //发起配对请求
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//配对状态
        registerReceiver(bluetoothReceiver, filter);
        checkPermiss();
    }

    LocalFileInfo localFileInfo;


    BluetoothAdapter mBluetoothAdapter;

    MultiStateView multiplestatusView;
    RecyclerView recyclerview, recyclerview_binded;
    MyBlueToothListAdapter adapter, adapter_binded;

    List<BluetoothDevice> divices = new ArrayList<>();
    List<BluetoothDevice> bindedDevices = new ArrayList<>();

    //初始化控件
    private void initView() {
        setTitle("蓝牙连接");    //设置标题
        setLeftImgClickListener();  //设置左键返回
        setRightImgClickListener(R.drawable.ico_refresh);

        multiplestatusView = findViewById(R.id.multiplestatusView);
//        multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);    //页面初始化，默认为加载中状态
        multiplestatusView.setOnRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);
            }
        });

        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new MyBlueToothListAdapter(mContext, callBack);
        adapter.setData(divices);
        recyclerview.setAdapter(adapter);
        recyclerview.setHasFixedSize(true);
        recyclerview.setNestedScrollingEnabled(false);


        recyclerview_binded = findViewById(R.id.recyclerview_binded);
        recyclerview_binded.setLayoutManager(new LinearLayoutManager(mContext));
        adapter_binded = new MyBlueToothListAdapter(mContext, callBack);
        adapter_binded.setData(bindedDevices);
        recyclerview_binded.setAdapter(adapter_binded);
        recyclerview_binded.setHasFixedSize(true);
        recyclerview_binded.setNestedScrollingEnabled(false);

//        FscBleCentralApiImp  fscBleCentralApi = FscBleCentralApiImp.getInstance(this);
//        fscBleCentralApi.initialize();
//        if (fscBleCentralApi.isBtEnabled() == false) {
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, 2);
//        }
//        fscBleCentralApi.startScan(10000);
    }

    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            BluetoothDevice info = (BluetoothDevice) obj;
//            if (info.getBondState() == BluetoothDevice.BOND_NONE) {
//                //未配对的先配对
//                pinBlueTooth(info);  //配对
//            } else if (info.getBondState() == BluetoothDevice.BOND_BONDED) {
                //已配对的 连接，并发送数据
                    try {
                        Print_Dialog dialog = new Print_Dialog(mContext);
                        dialog.setData(info);
                        dialog.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//            }
//            if (localFileInfo != null) {
//                try {
//                    Bitmap bitmap = BitmapUtil.getSmallBitmap(localFileInfo.snapshot);
//                    Print_Dialog dialog = new Print_Dialog(mContext);
//                    dialog.setData(bitmap, info);
//                    dialog.show();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
        }
    };

    //获取已配对设备
    public void getBondDevice() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        bindedDevices.clear();
        for (BluetoothDevice device : pairedDevices) {
            int deviceClass = device.getBluetoothClass().getMajorDeviceClass();
            if (deviceClass == BluetoothClass.Device.Major.IMAGING) {
                bindedDevices.add(device);
                adapter_binded.notifyDataSetChanged();
            }
        }
    }

    /**
     * 扫描的方法 返回true 扫描成功
     * 通过接收广播获取扫描到的设备
     *
     * @return
     */
    public boolean scanBlue() {
        getBondDevice();
        divices.clear();

        if (!isBlueEnable()) {
            return false;
        }

        //当前是否在扫描，如果是就取消当前的扫描，重新扫描
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        //此方法是个异步操作，一般搜索12秒
        Log.i("开始扫描");
        return mBluetoothAdapter.startDiscovery();
    }


    /**
     * 配对（配对成功与失败通过广播返回）
     * ！！！弹出配对框
     *
     * @param device
     */
    public void pinBlueTooth(BluetoothDevice device) {
        if (device == null) {
            Log.e("设备不可以为空");
            return;
        }
        //配对之前把扫描关闭
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        //判断设备是否配对，没有配对在配，配对了就不需要配了
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {//BOND_NONE 没有配对状态
            Log.d("attemp to bond:" + device.getName());
            try {
                boolean returnValue = device.createBond();
                Log.e("是否配对成功：" + returnValue);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("配对失败");
            }
        }
    }


    /**
     * 设备是否支持蓝牙  true为支持
     *
     * @return
     */
    public boolean isSupportBlue() {
        return mBluetoothAdapter != null;
    }

    /**
     * 蓝牙是否打开   true为打开
     *
     * @return
     */
    public boolean isBlueEnable() {
        return isSupportBlue() && mBluetoothAdapter.isEnabled();
    }

    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                    startRefrsh();
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    stopRefrsh();
                    break;
                case BluetoothDevice.ACTION_FOUND:
//                    if (bindedDevices != null && bindedDevices.contains(device)) {
//                        return;
//                    }
                    Log.d("发现设备...");
                    if(!TextUtils.isEmpty(device.getName())) {
                        int deviceClass = device.getBluetoothClass().getMajorDeviceClass();
                        divices.add(device);
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case BluetoothDevice.ACTION_PAIRING_REQUEST:
                    Log.d("收到配对请求...");
                    break;
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                    switch (device.getBondState()) {
                        case BluetoothDevice.BOND_NONE:
                            Log.d("绑定失败");
                            CommToast.showToast(mContext, "配对失败");
                            break;
                        case BluetoothDevice.BOND_BONDING:
                            Log.d("绑定中");

                            break;
                        case BluetoothDevice.BOND_BONDED:
                            Log.d("绑定成功");
                            CommToast.showToast(mContext, "配对成功");
                            scanBlue();
                            break;
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    //点击事件
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent intent;
        switch (view.getId()) {
            case R.id.public_title_right_img:
                checkPermiss();
                break;
        }
    }

    //开始旋转动画
    private void startRefrsh() {
        ImageView iv = findViewById(R.id.public_title_right_img);
        if (iv.getAnimation() == null) {
            RotateAnimation ta = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
            ta.setDuration(500);
            ta.setInterpolator(new LinearInterpolator());
            ta.setRepeatCount(-1);
            iv.startAnimation(ta);
        }
    }

    //结束旋转动画
    private void stopRefrsh() {
        ImageView iv = findViewById(R.id.public_title_right_img);
        iv.clearAnimation();
    }

    protected void onDestroy() {
        super.onDestroy();//解除注册
        unregisterReceiver(bluetoothReceiver);
    }

    private void checkPermiss() {
        String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};
        List<String> denyPermissions = new ArrayList<>();
        for (String value : permission) {
            if (ContextCompat.checkSelfPermission(this, value) != PackageManager.PERMISSION_GRANTED) {//判断权限是否已授权
                //没有权限 就添加
                denyPermissions.add(value);
            }
        }
        if (denyPermissions != null && !denyPermissions.isEmpty()) {
            //申请权限授权
            ActivityCompat.requestPermissions(this, denyPermissions.toArray(new String[denyPermissions.size()]), 100);
        } else {
            //已全部授权
            //do something
            checkGPS();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请权限成功
                //do something
                checkGPS();
            } else {
                //权限被拒绝
                CommToast.showToast(mContext, "权限被拒绝，无法使用蓝牙功能");
            }
        }
    }

    // gps是否可用
    public static final boolean isGpsEnable(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public void checkGPS() {
        if (isGpsEnable(mContext)) {
            scanBlue();
        } else {
            //跳转到gps设置页
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 10011);
        }
    }
}
